package com.lbb.config;

import com.lbb.pojo.Configuration;
import com.lbb.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        //获取Document对象
        Document document = new SAXReader().read(inputStream);
        //获取根节点
        Element root_element = document.getRootElement();
        String namespace = root_element.attributeValue("namespace");
        //获取节点
        List<Element> list_select = root_element.selectNodes("//select");
        List<Element> list_delete = root_element.selectNodes("//delete");
        List<Element> list_update = root_element.selectNodes("//update");
        List<Element> list_insert = root_element.selectNodes("//insert");
        list_select.addAll(list_update);
        list_select.addAll(list_delete);
        list_select.addAll(list_insert);

        for(Element e:list_select){
            String id = e.attributeValue("id");
            String resultType = e.attributeValue("resultType");
            String paramterType = e.attributeValue("paramterType");
            String sql = e.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sql);
            String statementid = namespace + "." + id;
            configuration.getMappedStatementHashMap().put(statementid,mappedStatement);
        }

    }
}
